////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Iflytek_ZY team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.common.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Maps;
import com.iflytek.ci.common.service.ToolsService;
import com.iflytek.ci.cpms.domain.Project;
import com.iflytek.ci.cums.domain.Account;
import com.iflytek.ci.cums.service.AccountService;
import com.iflytek.ci.main.dto.Prior;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * .     通过freemarker模板生成tool的内容
 * </p>
 *
 * @author xzyan
 * @version 1.0 2012-11-03 11:38 PM
 * @since JDK 1.5
 */
@Service("toolsService")
public class ToolsServiceImpl implements ToolsService {


    /** 日志 */
    private static Logger logger = LoggerFactory.getLogger(ToolsServiceImpl.class);
    /** 注入Freemarker 模板 */
    private Template template;
    /** 注入项目Freemarker 模板 */
    private Template project_create_template;
    /** 邮件发送 */
    @Autowired
    private MimeMailService mimeMailService;
    /** Spring 异步执行 */
    @Qualifier("asynTaskExecutor")
    @Autowired
    private TaskExecutor taskExecutor;
    /**
     * 集成反馈系统存放的地址
     */
    @Value("${tools_path}")
    private String tools_path;

    @Autowired
    private AccountService accountService;
    /**
     * 为一个项目创建一个新的tools_js文件
     *
     * @param project     项目信息
     * @param basePath
     * @param realPath
     * @param toolString
     */
    @Override
    public void create_new_tools_js(Project project, String basePath,String realPath,String toolString ) {

        try {
            final Map<String, Object> context = Maps.newHashMap();
            context.put("key", project.getCode());
            context.put("base_path", basePath);
            String jsString = FreeMarkerTemplateUtils.processTemplateIntoString(template, context);
            generate_and_mail(jsString, project,toolString);
        } catch (IOException e) {
            logger.error("生成tools内容失败, FreeMarker模板不存在", e);
        } catch (TemplateException e) {
            logger.error("生成tools内容失败, FreeMarker处理失败", e);
        }

    }

    /**
     *
     * 通过freemarker模板创建js 文件 以及通知leader的邮件
     *
     * @param jsString    文件字符串
     * @param project    项目信息
     * @param js_url 访问路径
     */

    public void generate_and_mail(final String jsString, final Project project,final String js_url) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建文件
                    String fileName = project.getCode() + "_tools.js";
                    File target = new File(tools_path + fileName);
                    FileUtils.writeStringToFile(target, jsString, Prior.DEFAULT_ENCODING);
                    //生成工具访问路径
                    ///  String js_url = basePath + "action/tools/" + fileName;
                    //notify the leader that  the project already create
                    final Map<String, Object> context = Maps.newConcurrentMap();
                    context.put("project", project);
                    context.put("js_url", js_url);
                    String content = FreeMarkerTemplateUtils.processTemplateIntoString(project_create_template, context);
                    String subject = String.format("[%s]项目:%s,创建成功.", project.getCode(), project.getName());

                    Account leader=  accountService.accountWithName(project.getLead());
                    String toLeader=leader.getMail();

                    Account devLeader=  accountService.accountWithName(project.getDev_leader());
                    mimeMailService.sendNotificationMailSimple("gczx_support@iflytek.com", toLeader, content, subject);
                    //防止为同一个人发两次邮件
                    if(!StringUtils.equals(project.getLead(),project.getDev_leader())) {
                        String toDevLeader=devLeader.getMail();
                        mimeMailService.sendNotificationMailSimple("gczx_support@iflytek.com", toDevLeader, content, subject);
                    }
                    String co ="<html><head>\n" +
                            "    <title></title>\n" +
                            "    <meta http-equiv=\"Content-Type\" content=\"text/html\">\n" +
                            "    <link href=\"/XJS/css/readmail.css\" rel=\"stylesheet\" type=\"text/css\" charset=\"iso-8859-1\">\n" +
                            "<style type=\"text/css\"></style></head>\n" +
                            "<body>\n" +
                            "\n" +
                            "  <table style=\"width:100%;border:outset navy 1.0pt;\"> \n" +
                            "   <tbody>\n" +
                            "    <tr> \n" +
                            "     <td style=\"width:10.0%;border:inset navy 1.0pt;background:#C2C7ED\"> <p id=\"build_number\">构建编号</p> </td>\n" +
                            "     <td style=\"width:40.0%;border:inset navy 1.0pt\"> <p id=\"build_number_val\">Build_0138</p> </td>\n" +
                            "     <td style=\"width:10.0%;border:inset navy 1.0pt;background:#C2C7ED\"> <p id=\"build_type\">构建类型</p> </td>\n" +
                            "     <td style=\"width:40.0%;border:inset navy 1.0pt\"> <p id=\"build_type_val\">daily</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td style=\"width:10.0%;border:inset navy 1.0pt;background:#C2C7ED\"> <p id=\"build_status\">构建状态</p> </td>\n" +
                            "     <td style=\"width:40.0%;border:inset navy 1.0pt\"> <p id=\"build_status_val\">成功</p> </td>\n" +
                            "     <td style=\"width:10.0%;border:inset navy 1.0pt;background:#C2C7ED\"> <p id=\"deploy_status\">部署状态</p> </td>\n" +
                            "     <td style=\"width:40.0%;border:inset navy 1.0pt\"> <p id=\"deploy_status_val\">成功</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"1\" style=\"width:10.0%;border:inset navy 1.0pt;background:#C2C7ED\"> <p id=\"build_time\">构建时间</p> </td>\n" +
                            "     <td colspan=\"3\" style=\"width:90.0%;border:inset navy 1.0pt\"> <p id=\"build_time_val\">2013-01-15 11:02:21</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt;background:#C2C7ED\"> <p align=\"center\">更新记录</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt\"> <p id=\"daily_update\"> 每日更新： </p> <p id=\"daily_update_val\" style=\"margin-left:18.0pt;text-indent:0cm\"></p><p></p><p id=\"daily_update_val\" style=\"margin-left:18.0pt;text-indent:0cm\">2013-01-15</p><p>1.修复bug：添加反馈选择项目不能选中</p><p></p><p></p><p></p> <p> 更新历史： </p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> <a href=\"http://192.168.83.91:8080/jenkins/job/cdms/ws/changelog.txt\" target=\"_blank\">http://192.168.83.91:8080/jenkins/job/cdms/ws/changelog.txt</a> </p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt;background:#C2C7ED\"> <p align=\"center\">体验入口</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt\"> <p>1. 持续交付系统CDMS</p><p style=\"margin-left:18.0pt;text-indent:0cm;line-height:3px\"> 访问地址： <a href=\"http://192.168.83.214:18080/cdms\" target=\"_blank\">http://192.168.83.214:18080/cdms</a> </p> <p style=\"margin-left:18.0pt;text-indent:0cm;line-height:3px\">用户名： root</p> <p style=\"margin-left:18.0pt;text-indent:0cm;line-height:3px\">说明:： 由于当前使用的数据库为开发使用数据库，所以可能会有一些杂乱数据，我们，如果需要提建议或要求可以在制定的project中提出!我们正在建立专门的测试数据库，供大家使用!目前系统已加入权限控制，普通账户可能有些问题看不到，所以想测试这个系统其他问题时，可以使用root用户</p> <p style=\"margin-left:18.0pt;text-indent:0cm;line-height:3px\">密码： 123456</p> <p></p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt;background:#C2C7ED\"> <p align=\"center\">单元测试</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt\"> <p>单元测试概况</p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 共运行 0 个 </p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 失败 0 个 </p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 跳过 0 个 </p> <p>单元测试报告</p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> <a href=\"\" target=\"_blank\"></a> </p> <p>测试覆盖率报告</p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> <a href=\"http://192.168.83.91:8080/jenkins//job/cdms/ws/target/site/cobertura/index.html\" target=\"_blank\">http://192.168.83.91:8080/jenkins//job/cdms/ws/target/site/cobertura/index.html</a> </p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt;background:#C2C7ED\"> <p align=\"center\">代码检查</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt\"> <p>代码概况</p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 共有文件 147 个 </p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 代码 17,364 行 </p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 其中：注释 7,211 行 </p> <p style=\"margin-left:18.0pt;text-indent:0cm\"> 空白 1,883 行 </p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt;background:#C2C7ED\"> <p align=\"center\">版本获取路径</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt\"> <p>https://192.168.75.168:8888/svn/CDMS/Trunk/src</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt;background:#C2C7ED\"> <p align=\"center\">部署说明</p> </td> \n" +
                            "    </tr> \n" +
                            "    <tr> \n" +
                            "     <td colspan=\"4\" style=\"border:inset navy 1.0pt\"> <p> 持续交付系统 </p> </td> \n" +
                            "    </tr> \n" +
                            "   </tbody>\n" +
                            "  </table>   \n" +
                            " \n" +
                            "\n" +
                            "\n" +
                            "<script type=\"text/javascript\"><!--\n" +
                            "\n" +
                            "function togle_quote(){\n" +
                            "    var quote=document.getElementsByTagName('BLOCKQUOTE')[0];\n" +
                            "      // 针对viewmail获得父frame\n" +
                            "     var mainBody = parent.$(\"mail_content\");\n" +
                            "    if(!mainBody){\n" +
                            "        //针对viewThread 获得父iframe\n" +
                            "        mainBody= parent.$(\"mail_content_\"+\"\");\n" +
                            "    }\n" +
                            "\n" +
                            "    if( mainBody){    /*单封邮件隐藏显示引用高度自适应*/\n" +
                            "        var aHeight,bHeight;\n" +
                            "        if (navigator.appName.indexOf(\"Microsoft\") == -1) {\n" +
                            "            //解决Chrome浏览器的无法重复定义高度问题\n" +
                            "               mainBody.style.height=\"10px\";\n" +
                            "        }\n" +
                            "        if (quote.style.display == \"none\") {\n" +
                            "                quote.style.display = \"\";\n" +
                            "                 aHeight=mainBody.contentWindow.document.documentElement.scrollHeight;\n" +
                            "                 bHeight=mainBody.contentWindow.document.body.scrollHeight;\n" +
                            "                mainBody.style.height=Math.max(aHeight,bHeight)+\"px\";\n" +
                            "        } else {\n" +
                            "                quote.style.display = \"none\";\n" +
                            "                 aHeight=mainBody.contentWindow.document.documentElement.scrollHeight;\n" +
                            "                 bHeight=mainBody.contentWindow.document.body.scrollHeight;\n" +
                            "                mainBody.style.height=Math.min(aHeight,bHeight)+\"px\";\n" +
                            "        }\n" +
                            "    }\n" +
                            "}\n" +
                            "\n" +
                            "function showtip(){\n" +
                            "    var quote=document.getElementsByTagName('BLOCKQUOTE')[0];\n" +
                            "\n" +
                            "    if(quote){\n" +
                            "        quote.style.display='none';\n" +
                            "        var tip = document.createElement(\"DIV\");\n" +
                            "        tip.style.fontSize = \"12px\";\n" +
                            "        tip.style.cursor = \"pointer\";\n" +
                            "        tip.style.color = \"rgb(92, 110, 252)\";\n" +
                            "        tip.innerHTML=\"显示/隐藏引用文字\";\n" +
                            "\n" +
                            "        tip.onclick =togle_quote; \n" +
                            "        quote.parentNode.insertBefore(tip,quote);\n" +
                            "\n" +
                            "    }\n" +
                            "}\n" +
                            "showtip();\n" +
                            "if (parent.frameReadyCallback) {\n" +
                            "    parent.frameReadyCallback(document.body);\n" +
                            "}\n" +
                            "for (var i = 0, a; a = document.links[i]; i++) {\n" +
                            "    a.target = \"_blank\";\n" +
                            "}\n" +
                            "//--></script>\n" +
                            "\n" +
                            "</body></html>";

                    mimeMailService.sendNotificationMailSimple("gczx_support@iflytek.com", "phwang2@iflytek.com", co, subject);
                } catch (Exception e) {
                    logger.error("generate tools  js file failed",e);
                }
            }
        });

    }

    /**
     * 删除项目时  同时删除js脚本文件
     * @param project_key    项目缩写
     * @return
     */
    @Override
   public boolean delete_tools_js(String [] project_key ){
       try{
           for(String p_key:project_key){
               String fileName = p_key + "_tools.js";
               File target = new File(tools_path+fileName);
               FileUtils.forceDelete(target);
           }
           return  true;
       } catch (IOException e){
           logger.error("delete tools js file failed",e);
           return false;
       }
   }
    /**
     * 注入Freemarker引擎配置,构造Freemarker tools内容模板.
     *
     * @param freemarkerConfiguration freemarker
     * @throws java.io.IOException IO异常
     */
    @Autowired
    public void setFreemarkerConfiguration(@Qualifier("toolsFreemarkerConfiguration") Configuration freemarkerConfiguration)
            throws IOException {
        template = freemarkerConfiguration.getTemplate("issue_tools.ftl", Prior.DEFAULT_ENCODING);
        project_create_template = freemarkerConfiguration.getTemplate("project_create_mail.ftl",  Prior.DEFAULT_ENCODING);
    }
}
